package com.uuah.server.exception;

import java.util.Map;

import com.uuah.config.i18n.Message;
import com.uuah.server.api.IUuahMessage;
import com.uuah.server.config.i18n.ServerMessages;
import com.uuah.server.message.UuahMessage;
import com.uuah.server.transport.NullPayload;
import com.uuah.server.transport.RequestContextHelper;

/**
 * <code>MessagingException</code> is a general message exception thrown when
 * errors specific to Message processing occur..
 *
 * <p>
 * update record:updator，update time，update content and version
 * </p>
 *
 * @author <a href="jonny_quan@hotmail.com">jonny</a>
 * @date 2009 2009-3-27 下午01:45:55
 * @version 1.0.0
 */
public class MessagingException extends AbstractUuahServerException {
	private static final long serialVersionUID = 6941498759267936649L;

	protected final transient IUuahMessage uuahMessage;

	public MessagingException(Message message, IUuahMessage uuahMessage) {
		super();
		this.uuahMessage = uuahMessage;
		setMessage(generateMessage(message));
	}

	public MessagingException(Message message, IUuahMessage uuahMessage,
			Throwable cause) {
		super(cause);
		this.uuahMessage = uuahMessage;
		setMessage(generateMessage(message));
	}

	public MessagingException(Message message, Object payload) {
		super();
		if (payload == null) {
			this.uuahMessage = RequestContextHelper.getEventContext()
					.getMessage();
		} else {
			this.uuahMessage = new UuahMessage(payload, (Map) null);
		}
		setMessage(generateMessage(message));
	}

	public MessagingException(Message message, Object payload, Throwable cause) {
		super(cause);
		if (payload == null) {
			this.uuahMessage = RequestContextHelper.getEventContext()
					.getMessage();
		} else {
			this.uuahMessage = new UuahMessage(payload, (Map) null);
		}
		setMessage(generateMessage(message));
	}

	private String generateMessage(Message message) {
		StringBuffer buf = new StringBuffer(80);

		if (message != null) {
			buf.append(message.getMessage()).append(". ");
		}

		if (uuahMessage != null) {
			Object payload = uuahMessage.getPayload();
			if (payload == null) {
				payload = NullPayload.getInstance();
			}

			buf.append(ServerMessages.messageIsOfType(payload.getClass())
					.getMessage());
		} else {
			buf.append("The current UuahMessage is null! ");
		}

		return buf.toString();
	}

	public IUuahMessage getUuahMessage() {
		return uuahMessage;
	}

}
